<?php
declare (strict_types=1);

namespace app\admin\model\base;

use aliyun\AliyunOss;
use app\BaseModel;
use think\facade\Cache;
use think\facade\Config;

/**
 * 系统配置表模型
 */
class SysConfig extends BaseModel
{
    /**
     * 默认缓存键
     * @var string
     */
    private static string $tKey = 'sys_config';

    /**
     * 系统配置枚举
     * @var array|array[]
     */
    public static array $sysConfig = [
        [
            'key' => 'WsOpenPlatform',
            'value' => ['name' => '', 'appid' => '', 'secret' => '', 'token' => '', 'aes_key' => ''],
            'remark' => '主体开放平台配置',
        ],
        [
            'key' => 'WsOfficialAccount',
            'value' => ['name' => '', 'appid' => '', 'secret' => '', 'token' => '', 'qrcode' => '',],
            'remark' => '主体公众号配置',
        ],
        [
            'key' => 'WsScanBag',
            'value' => [
                'douyin_client_key' => '', 'douyin_redirect_uri' => '', 'v1_iot_pay_uri' => '',
            ],
            'remark' => '取袋相关配置',
        ],
        [
            'key' => 'DataCenter',
            'value' => ['data_center_start' => 1, 'data_center_out_bag_num' => 2000000,],
            'remark' => '大屏数据优化',
        ],
    ];

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList(array $where, int $page, int $limit): array
    {
        $data = self::where($where)
            ->order('key asc')
            ->paginate(['list_rows' => $limit, 'page' => $page], false)
            ->toArray();
        $AliyunOss = new AliyunOss();
        //遍历数组
        foreach ($data['data'] as $k => &$v) {
            //解析value信息
            $v['value'] = json_decode($v['value'], true);
            //补充二维码图片信息
            if (isset($v['value']['qrcode'])) {
                $v['value']['qrcode_url'] = $AliyunOss->getObjectUrl($v['value']['qrcode']);
            }
        }
        return $data;
    }

    /**
     * 加载配置文件
     */
    public static function loadConfig()
    {
        $temp = [];
        //判断是否存在缓存
        if (!Cache::has(self::$tKey)) {
            //查询数据库
            $data = self::field('key,value')->select()->toArray();
            foreach ($data as $v) {
                $temp[$v['key']] = json_decode($v['value'], true);
            }
            //存入redis
            Cache::set(self::$tKey, $temp, 86400);
        }
        //批量设置参数
        $temp = Cache::get(self::$tKey);
        Config::set($temp, 'sys_config');
    }

    /**
     * 清除配置缓存
     */
    public static function cleanUpConfig()
    {
        Cache::delete(self::$tKey);
    }


}




